package com.sanjiaozhou.gameserver.config;

import com.sanjiaozhou.gameserver.utils.BusinessResult;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
//        Map<String, String> errors = new HashMap<>();
        List<String> msgList = new ArrayList<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
//            errors.put(error.getField(), error.getDefaultMessage());
            msgList.add(error.getDefaultMessage());
        });
        return ResponseEntity.badRequest().body(BusinessResult.fail(msgList.get(0)));
    }
}